﻿using Forum.Models;
using ForumBL;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using Forum.Filters;

namespace Forum.Controllers
{
    [AllowAnonymous]
    public class AuthenticationController : Controller
    {

        [HttpGet]
        public ActionResult LogIn()
        {
            return View();
        }


        [HttpPost]
        public ActionResult LogIn(LoginModel model)
        {

            if (ModelState.IsValid)
            {
                UserBL userContext = new UserBL();

                if (userContext.IsValidUser(new ForumDomainModels.User(model.Username,model.Password)))
                {
                    ForumDomainModels.User user = 
                        userContext.GetUserByUsernameAndPassword(new ForumDomainModels.User(model.Username, model.Password));
                    this.HttpContext.Session["Id"] = user.Id;
                    this.HttpContext.Session["Username"] = user.Username;
                    return RedirectToAction("Index", "Home");
                }
                else
                {
                    ModelState.AddModelError(
                        "", "Invalid username or password, please try again");
                    return View();
                }

            }
            else
            {
                return View();
            }

        }


        [HttpGet]
        public ActionResult LogOut()
        {
            this.HttpContext.Session["Id"] = null;
            this.HttpContext.Session["Username"] = null;
            return RedirectToAction("Index", "Arbitrator");
        }


        [HttpGet]
        public ActionResult Register()
        {
            return View();
        }


        [HttpPost]
        public ActionResult Register(RegisterModel model)
        {
            UserBL userContext = new UserBL();
            if (ModelState.IsValid)
            {
                ForumDomainModels.User user = new ForumDomainModels.User();
                user.Username = model.Username;
                user.Password = model.Password;
                user.FirstName = model.FirstName;
                user.LastName = model.LastName;
                user.Age = model.Age;
                user.IsAdmin = false;
                user.DateRegistered = DateTime.Now;
                userContext.InsertUser(user);
                return RedirectToAction("Index", "Arbitrator");
            }
            else
            {
                ModelState.AddModelError("", "Please fill correct data");
                return View();
            }
        }

    }
}
